package com.lj.ljminsu.interceptor;

import com.lj.ljminsu.bean.TjUser;
import com.lj.ljminsu.bean.UserThreadLocal;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getParameter("token");

        if (!"null".equals(token)&&null!=token) {
            try {
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("qianfeng");
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                Claims body = claimsJws.getBody();
                String username = body.getSubject();
                String id = body.getId();
                TjUser tjUser = new TjUser();
                tjUser.setUserPhone(username);
                tjUser.setUserId(Long.parseLong(id));
                UserThreadLocal.set(tjUser);
                Object role = body.get("role");

                return true;
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
            } catch (UnsupportedJwtException e) {
                e.printStackTrace();
            } catch (MalformedJwtException e) {
                e.printStackTrace();
            } catch (SignatureException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        response.sendError(401,"登录错误");
//       response.sendRedirect("http://localhost:8080/intercept/");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.set(null);
    }
}
